package com.netease.commenta.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * Created by Ben on 2017/2/26.
 */

public class FixedListView extends ListView {
    public FixedListView(Context context) {
        super(context);
    }

    public FixedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FixedListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        fixHeight();
    }

    private void fixHeight() {
        ListAdapter adapter = this.getAdapter();
        int totalHeight = 0;
        if (adapter != null) {
            for (int i = 0; i < adapter.getCount(); i++) {
                View item = adapter.getView(i, null, this);
                item.measure(0, 0);
                totalHeight += item.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = totalHeight + getDividerHeight() * (getCount() - 1)
                + getPaddingTop() + getPaddingBottom();
        setLayoutParams(params);
    }
}
